home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / tempfile.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  19KB  |  638 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Temporary files.
  5.  
  6. This module provides generic, low- and high-level interfaces for
  7. creating temporary files and directories.  The interfaces listed
  8. as "safe" just below can be used without fear of race conditions.
  9. Those listed as "unsafe" cannot, and are provided for backward
  10. compatibility only.
  11.  
  12. This module also provides some data items to the user:
  13.  
  14.   TMP_MAX  - maximum number of names that will be tried before
  15.              giving up.
  16.   template - the default prefix for all temporary names.
  17.              You may change this to control the default prefix.
  18.   tempdir  - If this is set to a string before the first use of
  19.              any routine from this module, it will be considered as
  20.              another candidate location to store temporary files.
  21. '''
  22. __all__ = [
  23.     'NamedTemporaryFile',
  24.     'TemporaryFile',
  25.     'SpooledTemporaryFile',
  26.     'mkstemp',
  27.     'mkdtemp',
  28.     'mktemp',
  29.     'TMP_MAX',
  30.     'gettempprefix',
  31.     'tempdir',
  32.     'gettempdir']
  33. import os as _os
  34. import errno as _errno
  35. from random import Random as _Random
  36.  
  37. try:
  38.     from cStringIO import StringIO as _StringIO
  39. except ImportError:
  40.     from StringIO import StringIO as _StringIO
  41.  
  42.  
  43. try:
  44.     import fcntl as _fcntl
  45. except ImportError:
  46.     
  47.     def _set_cloexec(fd):
  48.         pass
  49.  
  50.  
  51.  
  52. def _set_cloexec(fd):
  53.     
  54.     try:
  55.         flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
  56.     except IOError:
  57.         pass
  58.  
  59.     flags |= _fcntl.FD_CLOEXEC
  60.     _fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
  61.  
  62.  
  63. try:
  64.     import thread as _thread
  65. except ImportError:
  66.     import dummy_thread as _thread
  67.  
  68. _allocate_lock = _thread.allocate_lock
  69. _text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
  70. if hasattr(_os, 'O_NOINHERIT'):
  71.     _text_openflags |= _os.O_NOINHERIT
  72.  
  73. if hasattr(_os, 'O_NOFOLLOW'):
  74.     _text_openflags |= _os.O_NOFOLLOW
  75.  
  76. _bin_openflags = _text_openflags
  77. if hasattr(_os, 'O_BINARY'):
  78.     _bin_openflags |= _os.O_BINARY
  79.  
  80. if hasattr(_os, 'TMP_MAX'):
  81.     TMP_MAX = _os.TMP_MAX
  82. else:
  83.     TMP_MAX = 10000
  84. template = 'tmp'
  85. _once_lock = _allocate_lock()
  86. if hasattr(_os, 'lstat'):
  87.     _stat = _os.lstat
  88. elif hasattr(_os, 'stat'):
  89.     _stat = _os.stat
  90. else:
  91.     
  92.     def _stat(fn):
  93.         
  94.         try:
  95.             f = open(fn)
  96.         except IOError:
  97.             raise _os.error
  98.  
  99.         f.close()
  100.  
  101.  
  102. def _exists(fn):
  103.     
  104.     try:
  105.         _stat(fn)
  106.     except _os.error:
  107.         return False
  108.  
  109.     return True
  110.  
  111.  
  112. class _RandomNameSequence:
  113.     '''An instance of _RandomNameSequence generates an endless
  114.     sequence of unpredictable strings which can safely be incorporated
  115.     into file names.  Each string is six characters long.  Multiple
  116.     threads can safely use the same instance at the same time.
  117.  
  118.     _RandomNameSequence is an iterator.'''
  119.     characters = 'abcdefghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + '0123456789_'
  120.     
  121.     def __init__(self):
  122.         self.mutex = _allocate_lock()
  123.         self.rng = _Random()
  124.         self.normcase = _os.path.normcase
  125.  
  126.     
  127.     def __iter__(self):
  128.         return self
  129.  
  130.     
  131.     def next(self):
  132.         m = self.mutex
  133.         c = self.characters
  134.         choose = self.rng.choice
  135.         m.acquire()
  136.         
  137.         try:
  138.             letters = [ choose(c) for dummy in '123456' ]
  139.         finally:
  140.             m.release()
  141.  
  142.         return self.normcase(''.join(letters))
  143.  
  144.  
  145.  
  146. def _candidate_tempdir_list():
  147.     '''Generate a list of candidate temporary directories which
  148.     _get_default_tempdir will try.'''
  149.     dirlist = []
  150.     for envname in ('TMPDIR', 'TEMP', 'TMP'):
  151.         dirname = _os.getenv(envname)
  152.         if dirname:
  153.             dirlist.append(dirname)
  154.             continue
  155.     
  156.     if _os.name == 'riscos':
  157.         dirname = _os.getenv('Wimp$ScrapDir')
  158.         if dirname:
  159.             dirlist.append(dirname)
  160.         
  161.     elif _os.name == 'nt':
  162.         dirlist.extend([
  163.             'c:\\temp',
  164.             'c:\\tmp',
  165.             '\\temp',
  166.             '\\tmp'])
  167.     else:
  168.         dirlist.extend([
  169.             '/tmp',
  170.             '/var/tmp',
  171.             '/usr/tmp'])
  172.     
  173.     try:
  174.         dirlist.append(_os.getcwd())
  175.     except (AttributeError, _os.error):
  176.         dirlist.append(_os.curdir)
  177.  
  178.     return dirlist
  179.  
  180.  
  181. def _get_default_tempdir():
  182.     '''Calculate the default directory to use for temporary files.
  183.     This routine should be called exactly once.
  184.  
  185.     We determine whether or not a candidate temp dir is usable by
  186.     trying to create and write to a file in that directory.  If this
  187.     is successful, the test file is deleted.  To prevent denial of
  188.     service, the name of the test file must be randomized.'''
  189.     namer = _RandomNameSequence()
  190.     dirlist = _candidate_tempdir_list()
  191.     flags = _text_openflags
  192.     for dir in dirlist:
  193.         if dir != _os.curdir:
  194.             dir = _os.path.normcase(_os.path.abspath(dir))
  195.         
  196.         for seq in xrange(100):
  197.             name = namer.next()
  198.             filename = _os.path.join(dir, name)
  199.             
  200.             try:
  201.                 fd = _os.open(filename, flags, 384)
  202.                 fp = _os.fdopen(fd, 'w')
  203.                 fp.write('blat')
  204.                 fp.close()
  205.                 _os.unlink(filename)
  206.                 del fp
  207.                 del fd
  208.                 return dir
  209.             continue
  210.             except (OSError, IOError):
  211.                 e = None
  212.                 if e[0] != _errno.EEXIST:
  213.                     break
  214.                 
  215.                 e[0] != _errno.EEXIST
  216.             
  217.  
  218.         
  219.     
  220.     raise IOError, (_errno.ENOENT, 'No usable temporary directory found in %s' % dirlist)
  221.  
  222. _name_sequence = None
  223.  
  224. def _get_candidate_names():
  225.     '''Common setup sequence for all user-callable interfaces.'''
  226.     global _name_sequence
  227.     if _name_sequence is None:
  228.         _once_lock.acquire()
  229.         
  230.         try:
  231.             if _name_sequence is None:
  232.                 _name_sequence = _RandomNameSequence()
  233.         finally:
  234.             _once_lock.release()
  235.  
  236.     
  237.     return _name_sequence
  238.  
  239.  
  240. def _mkstemp_inner(dir, pre, suf, flags):
  241.     '''Code common to mkstemp, TemporaryFile, and NamedTemporaryFile.'''
  242.     names = _get_candidate_names()
  243.     for seq in xrange(TMP_MAX):
  244.         name = names.next()
  245.         file = _os.path.join(dir, pre + name + suf)
  246.         
  247.         try:
  248.             fd = _os.open(file, flags, 384)
  249.             _set_cloexec(fd)
  250.             return (fd, _os.path.abspath(file))
  251.         continue
  252.         except OSError:
  253.             e = None
  254.             if e.errno == _errno.EEXIST:
  255.                 continue
  256.             
  257.             raise 
  258.             continue
  259.         
  260.  
  261.     
  262.     raise IOError, (_errno.EEXIST, 'No usable temporary file name found')
  263.  
  264.  
  265. def gettempprefix():
  266.     '''Accessor for tempdir.template.'''
  267.     return template
  268.  
  269. tempdir = None
  270.  
  271. def gettempdir():
  272.     '''Accessor for tempfile.tempdir.'''
  273.     global tempdir
  274.     if tempdir is None:
  275.         _once_lock.acquire()
  276.         
  277.         try:
  278.             if tempdir is None:
  279.                 tempdir = _get_default_tempdir()
  280.         finally:
  281.             _once_lock.release()
  282.  
  283.     
  284.     return tempdir
  285.  
  286.  
  287. def mkstemp(suffix = '', prefix = template, dir = None, text = False):
  288.     """User-callable function to create and return a unique temporary
  289.     file.  The return value is a pair (fd, name) where fd is the
  290.     file descriptor returned by os.open, and name is the filename.
  291.  
  292.     If 'suffix' is specified, the file name will end with that suffix,
  293.     otherwise there will be no suffix.
  294.  
  295.     If 'prefix' is specified, the file name will begin with that prefix,
  296.     otherwise a default prefix is used.
  297.  
  298.     If 'dir' is specified, the file will be created in that directory,
  299.     otherwise a default directory is used.
  300.  
  301.     If 'text' is specified and true, the file is opened in text
  302.     mode.  Else (the default) the file is opened in binary mode.  On
  303.     some operating systems, this makes no difference.
  304.  
  305.     The file is readable and writable only by the creating user ID.
  306.     If the operating system uses permission bits to indicate whether a
  307.     file is executable, the file is executable by no one. The file
  308.     descriptor is not inherited by children of this process.
  309.  
  310.     Caller is responsible for deleting the file when done with it.
  311.     """
  312.     if dir is None:
  313.         dir = gettempdir()
  314.     
  315.     if text:
  316.         flags = _text_openflags
  317.     else:
  318.         flags = _bin_openflags
  319.     return _mkstemp_inner(dir, prefix, suffix, flags)
  320.  
  321.  
  322. def mkdtemp(suffix = '', prefix = template, dir = None):
  323.     """User-callable function to create and return a unique temporary
  324.     directory.  The return value is the pathname of the directory.
  325.  
  326.     Arguments are as for mkstemp, except that the 'text' argument is
  327.     not accepted.
  328.  
  329.     The directory is readable, writable, and searchable only by the
  330.     creating user.
  331.  
  332.     Caller is responsible for deleting the directory when done with it.
  333.     """
  334.     if dir is None:
  335.         dir = gettempdir()
  336.     
  337.     names = _get_candidate_names()
  338.     for seq in xrange(TMP_MAX):
  339.         name = names.next()
  340.         file = _os.path.join(dir, prefix + name + suffix)
  341.         
  342.         try:
  343.             _os.mkdir(file, 448)
  344.             return file
  345.         continue
  346.         except OSError:
  347.             e = None
  348.             if e.errno == _errno.EEXIST:
  349.                 continue
  350.             
  351.             raise 
  352.             continue
  353.         
  354.  
  355.     
  356.     raise IOError, (_errno.EEXIST, 'No usable temporary directory name found')
  357.  
  358.  
  359. def mktemp(suffix = '', prefix = template, dir = None):
  360.     """User-callable function to return a unique temporary file name.  The
  361.     file is not created.
  362.  
  363.     Arguments are as for mkstemp, except that the 'text' argument is
  364.     not accepted.
  365.  
  366.     This function is unsafe and should not be used.  The file name
  367.     refers to a file that did not exist at some point, but by the time
  368.     you get around to creating it, someone else may have beaten you to
  369.     the punch.
  370.     """
  371.     if dir is None:
  372.         dir = gettempdir()
  373.     
  374.     names = _get_candidate_names()
  375.     for seq in xrange(TMP_MAX):
  376.         name = names.next()
  377.         file = _os.path.join(dir, prefix + name + suffix)
  378.         if not _exists(file):
  379.             return file
  380.     
  381.     raise IOError, (_errno.EEXIST, 'No usable temporary filename found')
  382.  
  383.  
  384. class _TemporaryFileWrapper:
  385.     '''Temporary file wrapper
  386.  
  387.     This class provides a wrapper around files opened for
  388.     temporary use.  In particular, it seeks to automatically
  389.     remove the file when it is no longer needed.
  390.     '''
  391.     
  392.     def __init__(self, file, name, delete = True):
  393.         self.file = file
  394.         self.name = name
  395.         self.close_called = False
  396.         self.delete = delete
  397.  
  398.     
  399.     def __getattr__(self, name):
  400.         file = self.__dict__['file']
  401.         a = getattr(file, name)
  402.         if not issubclass(type(a), type(0)):
  403.             setattr(self, name, a)
  404.         
  405.         return a
  406.  
  407.     
  408.     def __enter__(self):
  409.         self.file.__enter__()
  410.         return self
  411.  
  412.     if _os.name != 'nt':
  413.         unlink = _os.unlink
  414.         
  415.         def close(self):
  416.             if not self.close_called:
  417.                 self.close_called = True
  418.                 self.file.close()
  419.                 if self.delete:
  420.                     self.unlink(self.name)
  421.                 
  422.             
  423.  
  424.         
  425.         def __del__(self):
  426.             self.close()
  427.  
  428.         
  429.         def __exit__(self, exc, value, tb):
  430.             result = self.file.__exit__(exc, value, tb)
  431.             self.close()
  432.             return result
  433.  
  434.     
  435.  
  436.  
  437. def NamedTemporaryFile(mode = 'w+b', bufsize = -1, suffix = '', prefix = template, dir = None, delete = True):
  438.     '''Create and return a temporary file.
  439.     Arguments:
  440.     \'prefix\', \'suffix\', \'dir\' -- as for mkstemp.
  441.     \'mode\' -- the mode argument to os.fdopen (default "w+b").
  442.     \'bufsize\' -- the buffer size argument to os.fdopen (default -1).
  443.     \'delete\' -- whether the file is deleted on close (default True).
  444.     The file is created as mkstemp() would do it.
  445.  
  446.     Returns an object with a file-like interface; the name of the file
  447.     is accessible as file.name.  The file will be automatically deleted
  448.     when it is closed unless the \'delete\' argument is set to False.
  449.     '''
  450.     if dir is None:
  451.         dir = gettempdir()
  452.     
  453.     if 'b' in mode:
  454.         flags = _bin_openflags
  455.     else:
  456.         flags = _text_openflags
  457.     if _os.name == 'nt' and delete:
  458.         flags |= _os.O_TEMPORARY
  459.     
  460.     (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
  461.     file = _os.fdopen(fd, mode, bufsize)
  462.     return _TemporaryFileWrapper(file, name, delete)
  463.  
  464. if _os.name != 'posix' or _os.sys.platform == 'cygwin':
  465.     TemporaryFile = NamedTemporaryFile
  466. else:
  467.     
  468.     def TemporaryFile(mode = 'w+b', bufsize = -1, suffix = '', prefix = template, dir = None):
  469.         '''Create and return a temporary file.
  470.         Arguments:
  471.         \'prefix\', \'suffix\', \'dir\' -- as for mkstemp.
  472.         \'mode\' -- the mode argument to os.fdopen (default "w+b").
  473.         \'bufsize\' -- the buffer size argument to os.fdopen (default -1).
  474.         The file is created as mkstemp() would do it.
  475.  
  476.         Returns an object with a file-like interface.  The file has no
  477.         name, and will cease to exist when it is closed.
  478.         '''
  479.         if dir is None:
  480.             dir = gettempdir()
  481.         
  482.         if 'b' in mode:
  483.             flags = _bin_openflags
  484.         else:
  485.             flags = _text_openflags
  486.         (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
  487.         
  488.         try:
  489.             _os.unlink(name)
  490.             return _os.fdopen(fd, mode, bufsize)
  491.         except:
  492.             _os.close(fd)
  493.             raise 
  494.  
  495.  
  496.  
  497. class SpooledTemporaryFile:
  498.     '''Temporary file wrapper, specialized to switch from
  499.     StringIO to a real file when it exceeds a certain size or
  500.     when a fileno is needed.
  501.     '''
  502.     _rolled = False
  503.     
  504.     def __init__(self, max_size = 0, mode = 'w+b', bufsize = -1, suffix = '', prefix = template, dir = None):
  505.         self._file = _StringIO()
  506.         self._max_size = max_size
  507.         self._rolled = False
  508.         self._TemporaryFileArgs = (mode, bufsize, suffix, prefix, dir)
  509.  
  510.     
  511.     def _check(self, file):
  512.         if self._rolled:
  513.             return None
  514.         max_size = self._max_size
  515.         if max_size and file.tell() > max_size:
  516.             self.rollover()
  517.         
  518.  
  519.     
  520.     def rollover(self):
  521.         if self._rolled:
  522.             return None
  523.         file = self._file
  524.         del self._TemporaryFileArgs
  525.         newfile.write(file.getvalue())
  526.         newfile.seek(file.tell(), 0)
  527.         self._rolled = True
  528.  
  529.     
  530.     def __enter__(self):
  531.         if self._file.closed:
  532.             raise ValueError('Cannot enter context with closed file')
  533.         self._file.closed
  534.         return self
  535.  
  536.     
  537.     def __exit__(self, exc, value, tb):
  538.         self._file.close()
  539.  
  540.     
  541.     def __iter__(self):
  542.         return self._file.__iter__()
  543.  
  544.     
  545.     def close(self):
  546.         self._file.close()
  547.  
  548.     
  549.     def closed(self):
  550.         return self._file.closed
  551.  
  552.     closed = property(closed)
  553.     
  554.     def encoding(self):
  555.         return self._file.encoding
  556.  
  557.     encoding = property(encoding)
  558.     
  559.     def fileno(self):
  560.         self.rollover()
  561.         return self._file.fileno()
  562.  
  563.     
  564.     def flush(self):
  565.         self._file.flush()
  566.  
  567.     
  568.     def isatty(self):
  569.         return self._file.isatty()
  570.  
  571.     
  572.     def mode(self):
  573.         return self._file.mode
  574.  
  575.     mode = property(mode)
  576.     
  577.     def name(self):
  578.         return self._file.name
  579.  
  580.     name = property(name)
  581.     
  582.     def newlines(self):
  583.         return self._file.newlines
  584.  
  585.     newlines = property(newlines)
  586.     
  587.     def next(self):
  588.         return self._file.next
  589.  
  590.     
  591.     def read(self, *args):
  592.         return self._file.read(*args)
  593.  
  594.     
  595.     def readline(self, *args):
  596.         return self._file.readline(*args)
  597.  
  598.     
  599.     def readlines(self, *args):
  600.         return self._file.readlines(*args)
  601.  
  602.     
  603.     def seek(self, *args):
  604.         self._file.seek(*args)
  605.  
  606.     
  607.     def softspace(self):
  608.         return self._file.softspace
  609.  
  610.     softspace = property(softspace)
  611.     
  612.     def tell(self):
  613.         return self._file.tell()
  614.  
  615.     
  616.     def truncate(self):
  617.         self._file.truncate()
  618.  
  619.     
  620.     def write(self, s):
  621.         file = self._file
  622.         rv = file.write(s)
  623.         self._check(file)
  624.         return rv
  625.  
  626.     
  627.     def writelines(self, iterable):
  628.         file = self._file
  629.         rv = file.writelines(iterable)
  630.         self._check(file)
  631.         return rv
  632.  
  633.     
  634.     def xreadlines(self, *args):
  635.         return self._file.xreadlines(*args)
  636.  
  637.  
  638.